<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="depts" :props="defaultProps" :expand-on-click-node="false" default-expand-all>
        <template v-slot="{ data }">
          <el-row style="width:100%;height:40px" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <!-- 下拉菜单 -->
              <el-dropdown @command="operateDept($event, data)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 弹出对话框 -->
    <add-dept ref="deptRef" :current-node="currentNode" :show-dialog.sync="showDialog" @updateDepartmentList="updateDepartmentList" />
  </div>
</template>
<script>
import { getDepartmentList, delDepartment } from '@/api/department'
import { transformListToTreeData } from '@/utils'
import AddDept from './components/addDept.vue'
export default {
  name: 'Department',
  components: {
    AddDept
  },
  data() {
    return {
      depts: [],
      currentNode: null,
      showDialog: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    // 获取部门数据
    async getDepartmentList() {
      const result = await getDepartmentList()
      this.depts = transformListToTreeData(result, 0)
    },
    operateDept(type, data) {
      // 添加部门
      if (type === 'add') {
        // 显示添加部门对话框
        this.showDialog = true
        // 记录当前节点id
        this.currentNode = data.id
      } else if (type === 'edit') {
        this.showDialog = true
        this.currentNode = data.id
        this.$nextTick(() => {
          this.$refs.deptRef.getDepartmentDetail()
        })
      } else {
        this.$confirm('确定要删除该部门吗？', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' }).then(async() => {
          await delDepartment(data.id)
          // 删除成功后重新获取数据
          this.getDepartmentList()
          // 删除成功提示框
          this.$message.success('删除部门成功！')
        })
      }
    },
    updateDepartmentList() {
      this.getDepartmentList()
    }
  }
}
</script>
<style scoped>
.app-container {
  margin: 30px 140px;
  font-size: 14px;
}
.tree-manager{
  display: inline-block;
  padding-right: 10px;
  }
</style>
